import  $config from '/common/config.js'

function getUserInfo(){
	let value = uni.getStorageSync($config.USERINFO);
	if(value)
		value = JSON.parse(value);
	return value;
}

let nRequest=function(url,formData,response,efun,type="post",isLogin=false){
	uni.showLoading({
		title:'数据请求中...'
	})
	let user = getUserInfo();//getUser();
	url = $config.HOST+url;
	if(isLogin){
		if(!user)
		return uni.showModal({
			title:'登录提示',
			content:'还未登录，重新登录',
			success(e) {
				if(e.confirm){
					uni.switchTab({
						url:'/pages/login'
					})
				}
			}
		})
	}
	uni.request({
		url: url,
		header:{
			Authorization:user.api_token?user.api_token:''
		},
		data:formData,
		ContentType: 'json',
		method:type,
		success:function(res){
			uni.hideLoading();
			if(!res.data.success && (res.data.code == 401)){
				//用户信息失效后立马清除
				uni.setStorageSync($config.USERINFO,null);
				if(isLogin)
				uni.showModal({
					title:'登录提示',
					content: res.data.msg,
					success(e) {
						if(e.confirm){
							uni.switchTab({
								url:'/pages/login'
							})
						}
					}
				})
			}
			if(!res.data.success){
				return uni.showModal({
					title:'操作提示',
					content:res.data.msg?res.data.msg:'操作失败，请检查错误'
				})
			}
			if(typeof response == 'function')
				response(res);
		},
		fail:function(res){
			uni.hideLoading();
			uni.showToast({
				title:'数据发送失败，请检查网络或联系管理员'
			})
			if(typeof efun == 'function')
				efun(res);
		}
	})
};
let yRequest=function(url,formData,response,type="post",isLogin=true){
	nRequest(url,formData,response,type,true)
}

export default {nRequest,yRequest}